#include "LaserSensor.h"
#include <wiringPi.h>
#include <cjson/cJSON.h>

LaserSensor::LaserSensor(int deviceID, int pin, std::string dbName, std::string dataTableName, std::string configTableName)
	:Sensor(deviceID, dbName, dataTableName, configTableName),pin(pin)
{
}

bool LaserSensor::hasObstacles()
{
	return obstacles;
}

SensorConfig LaserSensor::readConfigFromBuffer()
{
	string configJson;
	SensorConfig config;
	if (buffer.readConfigJsonFromBuffer(configJson))
	{
		cout << "读取配置失败使用默认配置: sample = 1 \n";
		config.setSample(1);
		writeConfigToBuffer(config);
	}
	cJSON* configJsonObj = cJSON_Parse(configJson.c_str());
	cJSON* sample = cJSON_GetObjectItemCaseSensitive(configJsonObj, "sample");
	if (sample)
	{
		config.setSample(sample->valueint);
		cJSON_free(configJsonObj);
		cJSON_free(sample);
	}
		
	return config;
}

void LaserSensor::writeConfigToBuffer(SensorConfig config)
{

	cJSON* configObj = cJSON_CreateObject();
	cJSON* sample = cJSON_CreateNumber(config.getSample());
	cJSON_AddItemToObject(configObj, "sample", sample);

	this->buffer.writeConfigJsonToBuffer(cJSON_Print(configObj));

	cJSON_free(configObj);
	cJSON_free(sample);
}

void LaserSensor::recordSensorData()
{
	cJSON* laserObj = cJSON_CreateObject();
	cJSON* hasObstacles = cJSON_CreateNumber(obstacles);
	cJSON* date = cJSON_CreateString(this->buffer.getCurrentTime().c_str());

	cJSON_AddItemToObject(laserObj, "hasObstacles", hasObstacles);
	cJSON_AddItemToObject(laserObj, "date", date);
	buffer.writeDataJsonToBuffer(cJSON_Print(laserObj));

	cJSON_free(laserObj);
	cJSON_free(hasObstacles);
	cJSON_free(date);
}

void LaserSensor::readSensorData()
{
	pinMode(pin, INPUT);
	digitalWrite(pin, 0);

	if (digitalRead(pin) == LOW)
	{
		obstacles = true;
	}
	else
	{
		obstacles = false;
	}
}
